package com.food.restaurantpro.imageloader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.os.Handler;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {

	private MemoryCache m_MemoryCache;
	private FileCache m_FileCache;
	private Map<ImageView, String> m_ImageViewAndUrlMap;
	private ExecutorService m_ExecutorService;
	private Handler m_Handler;// handler to display images in UI thread
	private final int m_nIdDefaultAvatar;
	private int REQUIRED_SIZE = 1;

	/**
	 * 
	 * @param context
	 * @param idDefaultAvatar 
	 * @param requestSize : yeu cau ve chieu dai va chieu rong cua image. 
	 * Neu requestSize <= 1 thi lay dung kich thuoc cua anh goc
	 */
	public ImageLoader(Context context, int idDefaultAvatar, int requestSize) {
		m_MemoryCache = new MemoryCache();
		m_FileCache = new FileCache(context);
		m_ExecutorService = Executors.newFixedThreadPool(5);
		m_Handler = new Handler();
		m_ImageViewAndUrlMap = Collections
				.synchronizedMap(new WeakHashMap<ImageView, String>());
		m_nIdDefaultAvatar = idDefaultAvatar;
		REQUIRED_SIZE = requestSize;
	}

	/**
	 * Phuong thuc nay phai duoc goi trong onDestroy cua activity
	 * de giai phong bo nho cho app
	 * 
	 * Cach set nhu sau:
	 * 
	 * mListView.setAdapter(null);
	 * mAdapter.imageLoader.onDestroy();
	 * mAdapter = null;
	 * arrayList.clear();
	 * arrayList=null;		
	 */
	public void clearMemoryCache() {
		m_ExecutorService.shutdown();
		m_MemoryCache.clear();
		System.gc();
	}

	/**
	 * Chu y: Class nay cache image trong memory va cung luu xuong file
	 * Nen trong onDestroy cua activity thi phai goi clearMemoryCache
	 * de giai phong bo nho
	 */
	public void displayImage(String url, ImageView imageView) {
		// put imageview and url to map
		m_ImageViewAndUrlMap.put(imageView, url);
		// get bitmap from memorycache
		Bitmap bitmap = m_MemoryCache.get(url);
		if (bitmap != null)
			imageView.setImageBitmap(bitmap);
		else {
			// download queue
			queuePhotoDownloader(url, imageView);
			imageView.setImageResource(m_nIdDefaultAvatar);
		}
	}

	private void queuePhotoDownloader(String url, ImageView imageView) {
		ItemQueue itemQueue = new ItemQueue(url, imageView);
		m_ExecutorService.submit(new RunableDownloader(itemQueue));
	}

	// Task for the queue
	private class ItemQueue {
		public String url;
		public ImageView imageView;

		public ItemQueue(String u, ImageView i) {
			url = u;
			imageView = i;
		}
	}

	class RunableDownloader implements Runnable {
		ItemQueue itemQueue;

		RunableDownloader(ItemQueue itemQ) {
			this.itemQueue = itemQ;
		}

		@Override
		public void run() {
			try {
				if (imageViewReused(itemQueue))
					return;
				// get bitmap from cache in sdcard or download bitmap from web
				Bitmap bmp = getBitmapFromCacheOrDownloadBitmap(itemQueue.url);
				m_MemoryCache.put(itemQueue.url, bmp);
				if (imageViewReused(itemQueue))
					return;
				// update UI thread
				RunnableBitmapDisplayer bd = new RunnableBitmapDisplayer(bmp,
						itemQueue);
				m_Handler.post(bd);
			} catch (Throwable th) {
				th.printStackTrace();
			}
		}
	}

	private boolean imageViewReused(ItemQueue itemQueue) {
		String tag = m_ImageViewAndUrlMap.get(itemQueue.imageView);
		if (tag == null || !tag.equals(itemQueue.url))
			return true;
		return false;
	}

	// Used to display bitmap in the UI thread
	class RunnableBitmapDisplayer implements Runnable {
		Bitmap bitmap;
		ItemQueue itemQueue;

		public RunnableBitmapDisplayer(Bitmap b, ItemQueue i) {
			bitmap = b;
			itemQueue = i;
		}

		public void run() {
			if (imageViewReused(itemQueue))
				return;
			if (bitmap != null)
				itemQueue.imageView.setImageBitmap(bitmap);
			else
				itemQueue.imageView.setImageResource(m_nIdDefaultAvatar);
		}
	}

	private Bitmap getBitmapFromCacheOrDownloadBitmap(String url) {
		File f = m_FileCache.getFile(url);

		// from SD cache
		Bitmap b = decodeFile(f);
		if (b != null)
			return b;

		// from web
		try {
			Bitmap bitmap = null;
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			InputStream is = conn.getInputStream();
			OutputStream os = new FileOutputStream(f);
			// save file to m_FileCache
			copyStream(is, os);
			os.close();
			bitmap = decodeFile(f);
			return bitmap;
		} catch (Throwable ex) {
			ex.printStackTrace();
			if (ex instanceof OutOfMemoryError)
				m_MemoryCache.clear();
			return null;
		}
	}

	private void copyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	// decodes image and scales it to reduce memory consumption
	private Bitmap decodeFile(File f) {
		try {
			if (!f.exists()) {
				return null;
			}
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			FileInputStream stream1 = new FileInputStream(f);
			BitmapFactory.decodeStream(stream1, null, o);
			stream1.close();
			
			int scale = 1;
			//scale
			if(REQUIRED_SIZE > 1)
			{
				// Find the correct scale value. It should be the power of 2.
				int width_tmp = o.outWidth, height_tmp = o.outHeight;
				while (true) {
					if (width_tmp / 2 < REQUIRED_SIZE
							|| height_tmp / 2 < REQUIRED_SIZE)
						break;
					width_tmp /= 2;
					height_tmp /= 2;
					scale *= 2;
				}
			}
			
			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			FileInputStream stream2 = new FileInputStream(f);
			Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
			stream2.close();
			return bitmap;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Delete all memory cache and file cache
	 */
	public void clearCache() {
		m_MemoryCache.clear();
		m_FileCache.clear();
	}

}
